package com.sangu.dianxiu.task;

import android.os.AsyncTask;

import com.sangu.dianxiu.ISuccessCallback;
import com.sangu.dianxiu.utils.FileUtils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 下载语音的任务
 * Created by sg2 on 2016/1/13.
 */
public class DownloadVoiceAsyncTask extends AsyncTask<String ,Void ,String>{
    private ISuccessCallback iSuccessCallback;
    public DownloadVoiceAsyncTask() {
    }
    public DownloadVoiceAsyncTask(ISuccessCallback iSuccessCallback) {
        this.iSuccessCallback = iSuccessCallback;
    }
    @Override
    protected String doInBackground(String... params) {
        String voiceUrl=params[0];
        FileOutputStream fos=null;
        InputStream is=null;
        HttpURLConnection connection=null;
        try {
            URL url=new URL(voiceUrl);
            connection= (HttpURLConnection) url.openConnection();
            int responseCode=connection.getResponseCode();
            if(responseCode==200)
            {
                is=connection.getInputStream();
                fos=new FileOutputStream(FileUtils.getAppDownloadPath(voiceUrl));
                byte[] b=new byte[1024*1024];
                int length=0;
                while ((length=is.read(b))!=-1)
                {
                    fos.write(b,0,length);
                }
                fos.flush();
                connection.disconnect();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //下载成功后返回下载的文件的路径
        return FileUtils.getAppDownloadPath(voiceUrl).getAbsolutePath();
    }

    @Override
    protected void onPostExecute(String string) {
        super.onPostExecute(string);
        iSuccessCallback.success(string);
    }
}
